package com.fqgj.sentry.policy.engine.eval;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import com.fqgj.log.interfaces.Log;
import com.fqgj.log.factory.LogFactory;

import java.util.Date;

/**
 * Created by kennykong on 11/07/2017.
 */
public class EmbedGroovy {

    public static final Log LOGGER = LogFactory.getLog(EmbedGroovy.class);

    private EmbedGroovy() {

    }

    private static GroovyObject groovyObject = null;

    public static Object groovyMethodInvoke(String methodName, Object[] argz) {

        if (groovyObject == null) {
            ClassLoader parent = EmbedGroovy.class.getClassLoader();
            GroovyClassLoader loader = new GroovyClassLoader(parent);
//            String path = EmbedGroovy.class.getResource("/").toString();
//                    .replaceFirst("file:", "");
//            System.out.println(path);
            Class groovyClass = null;
//            File file = null;

//            file = new File("policy-engine/target/classes/script/GroovyShell.groovy");


            try {
//                file = new File("/home/fqgj/APP/risk_sentry_api/GroovyShell.groovy");
//                file = new File("/home/risk-api/api/GroovyShell.groovy");
                groovyClass = loader.loadClass("com.fqgj.sentry.policy.engine.eval.GroovyFunction");
//                        .parseClass(file);
            } catch (ClassNotFoundException e1) {
                e1.printStackTrace();
                LOGGER.error("Groovy class not found!");
            } catch (Exception e) {
                e.printStackTrace();
                LOGGER.error("Groovy file not find!");
            }

            try {
                groovyObject = (GroovyObject) groovyClass.newInstance();
            } catch (InstantiationException e) {
                LOGGER.error("Groovy Init Error!", e);
            } catch (IllegalAccessException e) {
                LOGGER.error("Groovy Access Error!", e);
            } catch (Exception e) {
                LOGGER.error("Groovy Eval Error!", e);
            }
        }
        Object object;
        try {
            object = groovyObject.invokeMethod(methodName, argz);
        } catch (Exception e) {
            LOGGER.error("groovy 解析异常，methodName：{}，argz：{}，异常信息为：{}", methodName, argz, e + e.toString());
            throw e;
        }
        return object;
    }

    public static void main(String args[]) throws Throwable {


        Object[] argz1 = {1, 2, 3};

        Object r = groovyMethodInvoke("weightScore", argz1);
        System.out.println(r);

        Object[] argz2 = {new Date(), new Date(2017 - 1900, 5, 10)};
        Object r1 = groovyMethodInvoke("gte", argz2);
        System.out.println(r1);

//        Object[] argz3 = {null, 2};
//        Object r2 = groovyMethodInvoke("lte", argz3);
//        System.out.println(r2);

        Object[] argz4 = {false, 1};
        Object r3 = groovyMethodInvoke("neq", argz4);
        System.out.println(r3);
    }

}
